<?php
/**
 * Created by PhpStorm.
 * User: function
 * Date: 2018-04-23
 * Time: 19:05
 */

namespace app\common\logic;
use app\common\logic\Logic;
use app\common\model\Favorite;
class FavoriteLogic extends Logic
{
    protected $modelClass = 'app\common\model\Favorite';
    protected $column = 'id,type,user_id';
//1是商品，2是公司，3是信息
    public function addFavorite($user_id,$type,$resource_id){
        
        $post = ['user_id'=>$user_id,'type'=>$type];
        switch ($type){
            case '1':
                $post['goods_id'] = $resource_id;
                $model = 'app\common\model\Goods';
                $thumbColumn = 'thumb';
                $titleColumn = 'title';
                break;
            case '2':
                $post['company_id'] = $resource_id;
                $model = 'app\common\model\Company';
                $thumbColumn = 'thumb';
                $titleColumn = 'company';
                break;
            case '3':
                $post['info_id'] = $resource_id;
                $model = 'app\common\model\Info';
                $thumbColumn = 'thumb';
                $titleColumn = 'title';
                break;
            default:
                error('收藏类别不符合预期');
                break;
        }
        
        $isHas = Favorite::get($post);
        if($isHas){
            error('无法重复收藏');
        }
        
        $m = new $model();
        $resource = $m::get($resource_id);
        
        if(!$resource){
            error('指定的资源不存在');
        }
        
        $post['thumb'] = $resource[$thumbColumn];
        $post['title'] = $resource[$titleColumn];
        
        $rt = $this->add($post);
        return $rt;
    }
    
    
    public function delFavorite($user_id,$type,$resource_id){
        
        $post = ['user_id'=>$user_id,'type'=>$type];
        switch ($type){
            case '1':
                $post['goods_id'] = $resource_id;
                break;
            case '2':
                $post['company_id'] = $resource_id;
                break;
            case '3':
                $post['info_id'] = $resource_id;
                break;
            default:
                error('收藏类别不符合预期');
                break;
        }
        
        $favorite = Favorite::get($post);
        if(!$favorite){
            error('您未收藏该资源');
        }
        
        $rt = $favorite->delete();
        return $rt;
    }
    
}